<?php
class Tag
{
	
	private $id = null;
	private $tag = null;
	
	function __construct($id = null, $tag = null)
	{
		$this->id = $id;
		$this->tag = $tag;
	}
	
	public static function load($id = "all", $article_id = null)
	{
		$db = new Database();
		
		// one tag, identified by its id
		if(is_numeric($id) and empty($article_id))
		{
			$ar['id'] = $id;
		
			$db->select("tags",'*',$ar, '1');
			$data = $db->fetch();
		
			return new Tag($id,$data['tag']);
		}
		// one tag, identified by its name
		elseif(!is_numeric($id) and $id != "all" and !empty($id) and empty($article_id))
		{
			$ar['tag'] = $id;
		
			$db->select("tags",'*',$ar, '1');
			$data = $db->fetch();
		
			return new Tag($data['id'],$data['tag']);
		}
		// all the tags related to an article, in a TagSet
		elseif(is_numeric($article_id))
		{
			$ns = new TagSet();
			$ar['article_id'] = $article_id;
			$db->select("tag_join_article",'*',$ar);
			while($data = $db->fetch())
			{
				$ns->append(Tag::load($data['tag_id']));
			}
			return $ns;
		}
		// all tags
		else
		{
			$ns = new TagSet();
			$query = $db->select("tags");
			while($data = $db->fetch())
			{
				$ns->append(Tag::load($data['id']));
			}
			return $ns;
		}
	}
	
	##########################
	# Creates a NEW note and injects it into the database
	# Use : 1) set the variables with setter methods, 2) call this method
	# Param :
	# Returns :
	public function create()
	{
		$data['id'] = '';
		$data['tag'] = $this->getTag();
		$db = new Database();
		return $db->insert("tags",$data);
	}
	
	##########################
	# Check in the database if the given tag exists
	# Param : the name tag
	# Returns : true or false
	public static function isTag($tag)
	{
		$db = new Database();
		$ar['tag'] = $tag;
		$db->select("tags",'*',$ar);
		if($db->num_rows() > 0)
			return true;
		else
			return false;
	}
	
	##########################
	# Guess what tags should be associated with the given STRING
	# Param : String text
	# Returns : TagSet
	public static function matchTags($string)
	{
		// Get all the tags in the database
		$alltags = array();
		$tagset = Tag::load("all");
		foreach($tagset->getTags() as $tag)
			$alltags[] = $tag->getTag();
		
		// Get all the words in the $string
		$allwords = explode(" ", $string);
		
		// Clean the words, keeping only letters and digits
		foreach($allwords as &$word)
			$word = trim(preg_replace('/[^a-zA-Z0-9]/', '', $word));
		
		// Get the intersection of those arrays (i.e. all the words being tags)
		$intersection = array_intersect($alltags, $allwords);
		
		// Make the tagset
		$set = new TagSet();
		foreach($intersection as $tagname)
			$set->append(Tag::load($tagname));
		
		// Return
		return $set;
	}
	
	##########################
	# Setters
	public function setId($id) { $this->id = $id; }
	public function setTag($tag) { $this->tag = $tag; }
	
	##########################
	# Getters
	public function getId() { return $this->id; }
	public function getTag() { return $this->tag; }

	
}
?>